<?php
namespace app\admin\controller;

use app\admin\BaseController;
use think\facade\View;
use think\facade\Db;
use think\facade\Session;

class Login extends BaseController{
	
	/**
     * 登录页面
     * @access public
     */
	public function login()
    {
    	if(session('?admin')){
    		return redirect('index/index');
    	}else{
    		return View::fetch('login/login');
    	}       
    }
	
	
	/**
     * 登录方法
     * @access public
     */
	public function doLogin()
	{
		$params = $this->request->post();
		$params = json_decode($params['data'],true);
		$this -> validate($params,'app\\admin\\validate\\Login.login');
		$admin = Db::name('admin')->where(['username'=>$params['username'],'password'=>md5($params['password'])])->find();
		if(!$admin){
			return make_json_response('',false,'用户名或密码错误');
		}
		session('admin', $admin['id']);
		Session::save();
		return make_json_response('',true,'登录成功');
	}
	
	/**
     * 修改密码页面
     * @access public
     */
	public function resetpw()
	{
		Session::clear();
		return View::fetch('login/resetpw');
	}
	
	/**
     * 修改密码方法
     * @access public
     */
	public function doResetpw()
	{
		$params = $this->request->post();
		$params = json_decode($params['data'],true);
		$this -> validate($params,'app\\admin\\validate\\Login.resetpw');
		$admin = Db::name('admin')->where(['password'=>md5($params['ypassword'])])->find();
		if(!$admin){
			return make_json_response('',false,'原密码错误');
		}
		if($params['newpassword'] != $params['renewpassword']){
			return make_json_response('',false,'两次密码不一致');
		}
		$re = Db::name('admin')->where(['password'=>md5($params['ypassword'])])->update(['password'=>md5($params['newpassword'])]);
		if($re){
			return make_json_response('',true,'修改成功，请重新登录');
		}else{
			return make_json_response('',false,'修改失败');
		}	
	}
	
	
	/**
     * 退出登录
     * @access public
     */
    public function loginOut(){
    	Session::clear();
        return redirect('login/login');
    }
}
